#region License

// This file is part of Grawlix.
// 
// Grawlix is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
// Grawlix is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public
// License along with Grawlix.  If not, see
// <http://www.gnu.org/licenses/>.

#endregion

using System;
using System.Threading;

namespace Grawlix.Concurrency
{
	/// <summary>
	/// A helper class used to assert thread affinity.
	/// </summary>
	public class ThreadAffinity
	{
		/// <summary>
		/// The affine thread's managed thread identifier.
		/// </summary>
		private readonly int _threadId =
			Thread.CurrentThread.ManagedThreadId;

		/// <summary>
		/// Asserts the current thread is the same as this object was
		/// created on.
		/// </summary>
		/// <exception cref="InvalidOperationException">
		/// The current thread is not the same as the affine thread..
		/// </exception>
		public void AssertCurrent()
		{
			int id = Thread.CurrentThread.ManagedThreadId;
			if (id != _threadId)
			{
				throw new InvalidOperationException(
					"An attempt was made to invoke an operation that has " +
					"affinity to a particular thread (id = " + _threadId +
					"), but " +
					"the call was made on a separate thread (id = " +
					_threadId + "). " +
					"Make sure that operations with thread affinity are " +
					"called on the appropriate thread.");
			}
		}
	}
}